'use strict';
const db = uniCloud.database();
const dbCollectionName = 'zhy_business_info';
exports.main = async (event, context) => {
	//event为客户端上传的参数
	console.log('event : ', event)
	switch (event.crud) {
		case 1:
			return add(event)
			break;
		case 2:
			return remove(event)
			break;
		case 3:
			return query(event)
			break;
		case 4:
			return update(event)
			break;
		case 5:
			// 增加备付金余额
			return businessAddReverveAmount(event)
			break;
	}

	//返回数据给客户端
	return event
};
async function update(event) {
	if (event.formId == null || event.formId == undefined) {
		// 查询出businessInfo的id
		let originalBusinessInfo = await query(event.data)
		if (originalBusinessInfo != null && originalBusinessInfo.data != null &&
			originalBusinessInfo.data.length > 0) {
			event.formId = originalBusinessInfo.data[0]._id
		}
	}
	return await db.collection(dbCollectionName).doc(event.formId).update(event.data);
}

async function add(event) {
	return await db.collection(dbCollectionName).add(event.data);
}

async function query(params) {

	if (params == null || JSON.stringify(params) == "{}") {
		return {
			errSubject: 'param_lack',
			errCode: 0,
			errMsg: '参数不齐'
		}
	}
	let data = {};
	// db.collection(dbCollectionName).doc(params.create_opneid).update(value).then((res)
	await db.collection(dbCollectionName).where({
		create_wx_openid: params.create_wx_openid,
		create_alipay_openid: params.create_alipay_openid,
		_id: params._id,
		offlineBusinessId: params.offlineBusinessId,
	}).get().then((res) => {
		// res 为数据库查询结果
		console.log(JSON.stringify(res));
		data = res
		// let resData = res.result.data[0]
		// that.businessInfo = resData
	}).catch((err) => {
		// err.message 错误信息
		// err.code 错误码
	})
	return data;
}

async function businessAddReverveAmount(event) {
	if (objIsEmpty(event) || objIsEmpty(event.businessId) || objIsEmpty(event.amountFen)) {
		console.log('参数为空');
		return null
	}
	// 根据businessId查询
	let queryData = {
		offlineBusinessId: event.businessId
	}
	let businessInfoResult = await query(queryData)
	if (objIsEmpty(businessInfoResult) || objIsEmpty(businessInfoResult.data) ||
		businessInfoResult.data.length == 0) {
		console.log('无此商户id:' + event.businessId);
		return null
	}
	let business = businessInfoResult.data[0]
	if (objIsEmpty(business)) {
		console.log('无此商户id:' + event.businessId);
		return null
	}
	// 有商户：修改备付金余额
	let {
		_id,
		...businessInfo
	} = business
	console.log('修改前金额:' + businessInfo.reverse_amount);
	businessInfo.reverse_amount = parseInt(businessInfo.reverse_amount) + parseInt(event.amountFen)
	console.log('修改后金额:' + businessInfo.reverse_amount);
	return await db.collection(dbCollectionName).doc(_id).update(businessInfo)
}

function objIsEmpty(obj) {
	if (obj == undefined || obj == '' || obj == null || JSON.stringify(obj) == '{}') {
		return true
	}
	return false
}